#include "UART.h"
#include <xmc_uart.h>
#include "xmc_gpio.h"


#define UART_TX P2_5
#define UART_RX P2_2


XMC_GPIO_CONFIG_t uart_tx;
XMC_GPIO_CONFIG_t uart_rx;



const XMC_UART_CH_CONFIG_t uart_config = 
{	
  .data_bits = 8U,
  .stop_bits = 1U,
  .baudrate = 115200U
};


void UART_Init(void)
{
//	uart_tx.mode = XMC_GPIO_MODE_OUTPUT_PUSH_PULL_ALT2;
//	uart_tx.output_strength = XMC_GPIO_OUTPUT_STRENGTH_MEDIUM;
//	uart_rx.mode = XMC_GPIO_MODE_INPUT_TRISTATE;
//	XMC_GPIO_Init(UART_TX, &uart_tx);
//  XMC_GPIO_Init(UART_RX, &uart_rx);
	
	XMC_UART_CH_Init(XMC_UART0_CH1, &uart_config);
	XMC_GPIO_SetMode(UART_RX, XMC_GPIO_MODE_INPUT_PULL_UP);
  XMC_UART_CH_SetInputSource(XMC_UART0_CH1, XMC_UART_CH_INPUT_RXD, USIC0_C1_DX0_P2_2);

  /* Set service request for receive interrupt */
  XMC_USIC_CH_SetInterruptNodePointer(XMC_UART0_CH1, XMC_USIC_CH_INTERRUPT_NODE_POINTER_RECEIVE, 0U);
  XMC_USIC_CH_SetInterruptNodePointer(XMC_UART0_CH1, XMC_USIC_CH_INTERRUPT_NODE_POINTER_ALTERNATE_RECEIVE, 0U);
	
	
  //XMC_UART_CH_SetInputSource(XMC_UART0_CH1, XMC_UART_CH_INPUT_RXD, USIC0_C1_DX0_P2_2);
  //XMC_UART_CH_Start(XMC_UART0_CH1);
	
	NVIC_EnableIRQ(USIC0_1_IRQn);

  XMC_UART_CH_EnableEvent(XMC_UART0_CH1, XMC_UART_CH_EVENT_STANDARD_RECEIVE | XMC_UART_CH_EVENT_ALTERNATIVE_RECEIVE);

  XMC_UART_CH_Start(XMC_UART0_CH1);

  XMC_GPIO_SetMode(UART_TX, (XMC_GPIO_MODE_t)((int32_t)XMC_GPIO_MODE_OUTPUT_PUSH_PULL | (int32_t)P2_5_AF_U0C1_DOUT0));
	
}	


unsigned int CRC_CHECK(unsigned char *Buf, unsigned char CRC_CNT)
{
	unsigned int CRC_Temp;
	unsigned char i,j;
	CRC_Temp = 0xffff;

	for (i=0;i<CRC_CNT; i++)
  {      
		CRC_Temp ^= Buf[i];
		for (j=0;j<8;j++) 
    {
      if (CRC_Temp & 0x01)
          CRC_Temp = (CRC_Temp >>1 ) ^ 0xa001;
      else
          CRC_Temp = CRC_Temp >> 1; 
    }
  }
    return(CRC_Temp);
}


void OutPut_Data(uint32_t *speed)
{
	unsigned char i; 	
  unsigned char databuf[10] = {0};
  unsigned int CRC16 = 0;
	unsigned int temp[4] = {0};
	uint32_t speed_out[4];
	
	for(i=0;i<4;i++)
	{
		speed_out[i] = speed[i];
	}
	for(i=0;i<4;i++)
  {   
    temp[i]  = (int)speed_out[i];    
	}
 
	for(i=0;i<4;i++) 
	{
		databuf[i*2]   = (unsigned char)(temp[i]%256);
		databuf[i*2+1] = (unsigned char)(temp[i]/256);
	}
  
	CRC16 = CRC_CHECK(databuf,8);
	databuf[8] = CRC16%256;
	databuf[9] = CRC16/256;
	
	for(i=0;i<10;i++)
	{
		XMC_UART_CH_Transmit(XMC_UART0_CH1, databuf[i]);		
	}
		
}
